package org.example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;

public class DD_raw_uint16 {
    public static void main(String[] args) throws IOException {
        String inputPngPath = "D:\\Documents\\workspaces\\Gitee\\java-projects\\PictureProcess\\src\\main\\resources\\ame\\Snipaste.png";
        String outputRawPath = "output.raw";
        String outputPngPath = "output.png";

        // 步骤1: 读取PNG图片
        BufferedImage pngImage = ImageIO.read(new File(inputPngPath));

        // 步骤2: 转换PNG到16位黑白RAW
        convertToRaw16Grayscale(pngImage, outputRawPath);

        // 步骤4: 读取RAW文件并转换回PNG
        BufferedImage rawImage = convertFromRaw16Grayscale(outputRawPath, pngImage.getWidth(), pngImage.getHeight());
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(rawImage, "png", bos);
            byte[] byteArray = bos.toByteArray();
            new FileOutputStream("1111.png").write(byteArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void convertToRaw16Grayscale(BufferedImage image, String outputRawPath) throws IOException {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayscaleImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();

        // 获取灰度图像的像素数据
        byte[] pixels = ((DataBufferByte) grayscaleImage.getRaster().getDataBuffer()).getData();

        // 创建16位RAW图像数据
        short[] rawPixels = new short[width * height];
        for (int i = 0; i < pixels.length; i++) {
            // 将8位灰度值扩展到16位
            rawPixels[i] = (short) ((pixels[i] & 0xFF) << 8);
        }

        // 步骤3: 保存RAW文件
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(outputRawPath))) {
            for (short pixel : rawPixels) {
                dos.writeShort(pixel);
            }
        }
    }

    private static BufferedImage convertFromRaw16Grayscale(String outputRawPath, int width, int height) throws IOException {
        byte[] rawPixelsByte = new byte[width * height * 2];

        try (DataInputStream dis = new DataInputStream(new FileInputStream(outputRawPath))) {
            for (int i = 0; i < rawPixelsByte.length; i++) {
                rawPixelsByte[i] = dis.readByte();
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////

        // 检查bytes数组长度是否为偶数
        if (rawPixelsByte.length % 2 != 0) {
            throw new IllegalArgumentException("Byte array length must be even.");
        }
        // 创建short数组，长度为bytes数组长度的一半
        short[] rawPixelsShort = new short[rawPixelsByte.length / 2];

        // 遍历byte数组，每两个字节组成一个short值
        for (int i = 0; i < rawPixelsByte.length; i += 2) {
            // 将当前字节和下一个字节组合成一个short值
            // 注意：这里需要处理字节序（大端或小端）问题
            short value;
            // 大端字节序：先读取高位字节
            value = (short) ((rawPixelsByte[i] & 0xFF) << 8 | (rawPixelsByte[i + 1] & 0xFF));
            // 小端字节序：先读取低位字节
//            value = (short) ((rawPixelsByte[i + 1] & 0xFF) << 8 | (rawPixelsByte[i] & 0xFF));
            rawPixelsShort[i / 2] = value;
        }

        // 创建新的灰度图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
        WritableRaster raster = image.getRaster();
        DataBuffer dataBuffer = raster.getDataBuffer();
        if (dataBuffer instanceof DataBufferUShort) {
            short[] pixels = ((DataBufferUShort) dataBuffer).getData();
            System.arraycopy(rawPixelsShort, 0, pixels, 0, rawPixelsShort.length);
        }

        return image;
    }
}
